/*
 * @Description:
 * @Version: 2.0
 * @Autor: zhangjx
 * @Date: 2023-03-10 19:42:10
 * @LastEditors: uphldjx 1373577124@qq.com
 * @LastEditTime: 2024-05-25 22:19:09
 */
import axios, { type AxiosRequestConfig } from "axios";
import { close, start } from "@/utils/nprogress";

axios.defaults.withCredentials = true;
axios.defaults.headers.post["Content-Type"] = "application/json;charset=UTF-8";

const axiosInstance = axios.create({
  timeout: 10000 * 60,
  withCredentials: false,
});
let RequestStatus = true;

axiosInstance.defaults.baseURL =
  import.meta.env.MODE == "development" ? import.meta.env.VITE_BASE_API : "/";

const errorTip = (response?: any, tipMess?: string) => {
  console.log(showMessage(response.status, response.data!.msg), "msg");
};
axiosInstance.interceptors.request.use(
  (config: any) => {
    start();
    config.headers = {
      ...config.headers,
    };
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

axiosInstance.interceptors.response.use(
  (response) => {
    close();
    const status = response.status || 200;
    if (status === 200) {
      return Promise.resolve(response.data);
    } else {
      return Promise.reject(response.data);
    }
  },
  (error) => {
    const { response } = error;
    close();
    return Promise.reject(error);
  }
);

const request = <ResponseType = null>(
  url: string,
  options?: AxiosRequestConfig<unknown>
): Promise<ResponseType> => {
  return new Promise((resolve, reject) => {
    axiosInstance({
      url,
      ...options,
    })
      .then((res: any) => {
        resolve(res);
      })
      .catch((err) => reject(err));
  });
};

export { axiosInstance, request };

export const showMessage = (status: Number, msg: String) => {
  let message: String = "";
  switch (status) {
    case 400:
      message = "请求错误(400)";
      break;
    case 401:
      message = "未授权，请重新登录(401)";
      break;
    case 403:
      message = "拒绝访问(403)";
      break;
    case 404:
      message = "请求出错(404)";
      break;
    case 408:
      message = "请求超时(408)";
      break;
    case 429:
      message = "请求太频繁,请稍后尝试(429)";
      break;
    case 501:
      message = "服务未实现(501)";
      break;
    case 502:
      message = "网络错误(502)";
      break;
    case 503:
      message = "服务不可用(503)";
      break;
    case 504:
      message = "网络超时(504)";
      break;
    case 505:
      message = "HTTP版本不受支持(505)";
      break;
    default:
      message = msg;
  }
  return `${message}`;
};
